package com.beiding.dao.impl;

import com.beiding.config.RedisConfig;
import com.beiding.timeout.dao.TaskMarkerSortedSet;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Repository;

@Repository
public class TaskMarkerSortedSetImpl implements TaskMarkerSortedSet {

    private ZSetOperations<String, Long> operations;

    public TaskMarkerSortedSetImpl(RedisConnectionFactory factory, StringRedisSerializer stringRedisSerializer, RedisConfig.LongRedisSerializer longRedisSerializer) {

        //定值redisTemplate
        RedisTemplate<String, Long> redisTemplate = new RedisTemplate<>();

        redisTemplate.setConnectionFactory(factory);

        //设置序列化器
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setValueSerializer(longRedisSerializer);
        redisTemplate.afterPropertiesSet();

        operations = redisTemplate.opsForZSet();
    }

    @Override
    public boolean contains(long time) {
        return operations.rangeByScore("test:taskMarker", time, time).size() == 1;
    }

    @Override
    public void add(long time) {
        operations.add("test:taskMarker", time, time);
    }

    @Override
    public Iterable<Long> lt(long time) {
        return operations.rangeByScore("test:taskMarker", 0, time - 1);
    }

    @Override
    public void remove(long time) {
        operations.remove("test:taskMarker", time);
    }
}
